class concurrencyLimit {
  constructor(limit = 5) {
    this.queue = new Set()
    this.limit = limit
  }
  add(promiseInvoker) {
    if (this.queue.size >= this.limit) {
      return new Promise((resolve, reject) => {
        Promise.race(Array.from(this.queue))
          .catch(() => {})
          .finally(() => {
            this.add(promiseInvoker).then(resolve, reject)
          })
      })
    }
    let p = promiseInvoker()
    this.queue.add(p)
    p.catch(() => {}).finally(() => {
      this.queue.delete(p)
    })
    return p
  }
}
export default concurrencyLimit